import { defineStore } from "pinia"
import { getMenusApi } from "@/api"

export default defineStore("menus", {
  state(): {
    // 菜单
    menus: menusType[]
    // 权限
    perms: string[]
    // 树形菜单
    menusTree: menusType[]
    // 最终渲染的菜单
    showTree: menusType[]
  } {
    return {
      menus: [],
      perms: [],
      menusTree: [],
      showTree: []
    }
  },

  actions: {
    // 处理菜单,将其转化为tree结构
    changeTree(menus: menusType[], id: number | null) {
      return [...menus]
        .filter((res) => res.parentId == id)
        .map((item) => {
          item.children = this.changeTree(menus, item.id)
          return item
        })
    },

    // 根据权限隐藏没有权限的菜单
    showMenus(menus: menusType[], perms: string[]) {
      menus.forEach((res) => {
        // 如果权限为空, 则不用加权限
        if (!res.perms) return

        // 查看当前菜单是否有权限
        const is = perms.some((item) => {
          const reg = new RegExp(res.perms!)
          if (reg.test(item)) {
            return true
          }
        })

        if (!is) {
          res.isShow = 0
        }
      })
      return this.changeTree(menus, null)
    },

    // 获取真正渲染在页面的数组
    getMenus() {
      return new Promise(async (resolve) => {
        const res = await getMenusApi()
        const { perms, menus } = res

        // 将权限转存到仓库
        this.perms = perms
        this.menus = menus

        // 最终渲染器出的菜单
        this.showTree = this.showMenus(this.menus, perms)
        resolve(this.menus)
      })
    }
  }
})
